package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.constants.MQConstants;
import cn.itsource.hrm.domain.Pager;
import cn.itsource.hrm.feignclients.FastdfsFeignClient;
import cn.itsource.hrm.feignclients.RedisFeignClient;
import cn.itsource.hrm.mapper.PagerMapper;
import cn.itsource.hrm.mapper.SiteMapper;
import cn.itsource.hrm.service.IPagerService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.ZipUtils;
import cn.itsource.hrm.utils.VelocityUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sk
 * @since 2020-02-26
 */
@Service
public class PagerServiceImpl extends ServiceImpl<PagerMapper, Pager> implements IPagerService {

    @Autowired
    private FastdfsFeignClient fastdfsFeignClient ;

    @Autowired
    private RedisFeignClient redisFeignClient ;

    @Autowired
    private RabbitTemplate rabbitTemplate ;

    @Autowired
    private SiteMapper siteMapper ;

    //获取系统临时目录 ： C:\Users\ADMINI~1\AppData\Local\Temp\
    private String getTempDir(){
        String tempDir = System.getProperty("java.io.tmpdir");
        return tempDir;
    }
    //如果文件不存在就创建
    private File createFile(String path){
        try {
            File file = new File(path);
            if(!file.exists()){
                File parentFile = file.getParentFile();
                if(!parentFile.exists()){
                    //创建多级父目录
                    parentFile.mkdirs();
                }
                //创建文件
                file.createNewFile();
            }
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //pageName : home
    @Override
    public void pageStatic(String pageName, String redisDataKey) throws Exception {
        //1.基本参数判断
        if(!StringUtils.hasLength(pageName) || !StringUtils.hasLength(redisDataKey)){
            throw new RuntimeException("页面静态化失败，参数异常");
        }

        //2.准备模板==========================================
        //2.1.根据PageName查询Pager对象
        Pager pager = baseMapper.selectByName(pageName);

        //2.2.根据Pager里面的路径，去Fastdfs下载模板
        byte[] templateZipBytes = fastdfsFeignClient.download(pager.getTemplateUrl());
        if(templateZipBytes == null || templateZipBytes.length == 0){
            throw new RuntimeException("模板下载失败");
        }

        //把templateZipBytes写到磁盘 ：临时目录 , 要把“\” ,替换成 “/” , 不用，因为是自动获取的目录，不会有问题
        // C:\Users\ADMINI~1\AppData\Local\Temp\home.zip
        String zipPath = getTempDir()+pageName+".zip";

        //创建文件
        File zipFile = createFile(zipPath);

        //把byte下载到磁盘
        FileCopyUtils.copy(templateZipBytes , zipFile);

        //2.3.把下载的zip格式的模板解压 : C:\Users\ADMINI~1\AppData\Local\Temp\pagestatic
        String unZipDir = getTempDir()+"pagestatic/";

        ZipUtils.unZip(zipPath , unZipDir);

        //3.准备填充数据======================================
        //3.1.根据redisDataKey去Redis查询数据（map)
        AjaxResult ajaxResult = redisFeignClient.get(redisDataKey);
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            throw new RuntimeException("数据获取失败");
        }
        //转成list?
        String dataString = ajaxResult.getResultObj().toString();
        Map<String,Object> model = JSON.parseObject(dataString,Map.class);

        //3.2.zip解压的路径作为staticRoot参数的值
        // unZipDir :C:\Users\Administrator\AppData\Local\Temp\pagestatic
        model.put("staticRoot",unZipDir);

        //4.合并模板==========================================
        //4.1.数据和模板作为参数
        //4.2.使用模板引擎合并模板成html
        //解压后的真实模板的全路径 ： C:\Users\Administrator\AppData\Local\Temp\pagestatic\home.vm
        String templatePath = unZipDir+pageName+".vm";
        //合并后的html保存路径 ：  C:\Users\Administrator\AppData\Local\Temp\pagestatic\home.html
        String htmlPath = unZipDir+pageName+".html";

        VelocityUtils.staticByTemplate(model , templatePath ,htmlPath);

        //5.推送html==========================================
        //5.1.把html上传到Fastdfs ， 拿到上传路径
        byte[] htmlBytes = FileCopyUtils.copyToByteArray(new File(htmlPath));
        AjaxResult htmlUploadResult = fastdfsFeignClient.uploadBytes(htmlBytes, "html");
        if(!htmlUploadResult.isSuccess() || htmlUploadResult.getResultObj() == null){
            throw new RuntimeException("页面静态化失败，html上传失败");
        }

        //5.2.集成MQ，往MQ发送消息
        // 内容：1.html的fastdfs的下载路径， 2.html需要拷贝到Nginx的物理路径
        //html路径
        String htmlPathInFastdfs = htmlUploadResult.getResultObj().toString();
        //Nginx的物理路径
        String physicalPath = pager.getPhysicalPath();
        Map<String,String > mqMessage = new HashMap<>();
        mqMessage.put("htmlPathInFastdfs",htmlPathInFastdfs);
        mqMessage.put("physicalPath",physicalPath);

        //routingkey :当前pager对应的站点的sn.
        String routingKey =  siteMapper.selectById(pager.getSiteId()).getSn() ;

        //发送消息到MQ
        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_PAGE_DIRECT ,routingKey,mqMessage);
    }
}
